<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!--添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" style="width:100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 使用栅格布局 -->
            <el-row
              :class="['bdbottom',index===0?'bdtop':'','vcenter']"
              v-for="(item1,index) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for 循环 嵌套渲染二级权限 -->
                <el-row
                  :class="[index===0?'':'bdtop','vcenter']"
                  v-for="(item2,index) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small">编辑</el-button>
            <el-button type="danger" icon="el-icon-search" size="small">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限"  :visible.sync="setRightDialogVisible" width="30%">
      <!-- 树形控件 -->
      <el-tree ref="treeRef" show-checkbox  :default-checked-keys="defKeys" :default-expand-all="true" node-key="id" :data="rightsList"  :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data: () => {
    return {
      // 所有角色列表
      rolesList: [],
      // 控制分配权限的对话框
      setRightDialogVisible: false,
      // 所有权限列表
      rightsList: [],
      // 属性控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的 分配权限的内容
      defKeys: [],
      // 为分配权限提供一个id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const {
        data: { data, meta }
      } = await this.$http.get('/roles')
      if (meta.status !== 200) return this.$message.error('获取用户列表失败')
      // console.log(data, meta)
      // 为data中的 rolesList属性赋值
      this.rolesList = data
    },
    // 删除权限
    removeRightsById (role, rightId) {
      // 弹框提示用户是否要删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // roleID角色id  rightId权限id
          const {
            data: { data, meta }
          } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
          // console.log(roleId, rightId)
          if (meta.status !== 200) { return this.$message.error('删除用户的权限失败') }
          // console.log(data, meta)
          this.$message.success(meta.msg)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新列表
          // this.getRolesList() 不建议使用这个函数，因为会发生折叠的情况
          role.children = data
          // console.log(role, data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限的对话框
    async showSetRightDialog (row) {
      // 获取所有权限的数据
      const { data: { data, meta } } = await this.$http.get('/rights/tree')
      console.log(data, meta)
      if (meta.status !== 200) return this.$message.error('获取所有权限列表数据失败')
      // console.log('分配权限')
      this.rightsList = data
      // 获取默认选中的权限 先清空derKeys属性,不然会造成数据错乱
      this.defKeys = []

      this.getLeafKeys(row, this.defKeys)
      // 显示对话框
      this.setRightDialogVisible = true
      // console.log(row)
      // console.log(row.children)
      // 保存id供角色授权的时候使用
      this.roleId = row.id
    },
    // 通过递归的形式，获取角色下所有三级权限的id,并保存在defKeys数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(ele => {
        // eslint-disable-next-line no-undef
        return this.getLeafKeys(ele, arr)
      })
    },
    // 角色授权
    async allowRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      // 发送请求道后台
      const { data: { meta } } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (meta.status !== 200) return this.$message.error('更新角色权限失败')
      // console.log())
      // 关闭dialog
      this.setRightDialogVisible = false
      // 提示用户更新成功
      this.$message.success(meta.msg)
      // 刷新页面的数据
      this.getRolesList()
    }
  }
}
</script>
<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #ebeef5;
}
.bdbottom {
  border-bottom: 1px solid #ebeef5;
}
.el-tag {
  margin: 7px;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
